package com.cx.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 *
 */
public class NioServer {

    static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {

        final ServerSocketChannel serverSocket = ServerSocketChannel.open();
        // 启动服务，绑定9000端口
        serverSocket.socket().bind(new InetSocketAddress(9000));
        // 设置serverSocket 为非阻塞
        serverSocket.configureBlocking(false);
        System.out.println("服务启动完成");
        while (true) {
            // 阻塞
            final SocketChannel socketChannel = serverSocket.accept();
            if (socketChannel != null) {
                // 如果有客户端连接
                System.out.println("连接成功" + socketChannel);
                // 设置 socketChannel 为非阻塞
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }
            final Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                final SocketChannel sc = iterator.next();

                final ByteBuffer buffer = ByteBuffer.allocate(128);
                final int len = sc.read(buffer);
                if (len > 0) {
                    System.out.println("接收到消息：" + new String(buffer.array()));
                } else if (len == -1) {
                    iterator.remove();
                    System.out.println("客户端断开");
                }
            }
        }
    }
}
